<template>
  <el-form
    :model="gameForm"
    :rules="rules"
    label-width="120px"
    label-position="left"
  >
    <el-form-item label="游戏标题" prop="title">
      <el-input
        v-model="gameForm.title"
        placeholder="请输入游戏名称"
        clearable
      />
    </el-form-item>

    <el-form-item label="游戏描述" prop="description">
      <el-input
        v-model="gameForm.description"
        type="textarea"
        :rows="4"
        placeholder="请输入游戏详细描述"
        maxlength="500"
        show-word-limit
      />
    </el-form-item>

    <el-form-item label="发行日期" prop="releaseDate">
      <el-date-picker
        :disabled="type === 1"
        v-model="gameForm.releaseDate"
        type="datetime"
        placeholder="选择发行日期"
        value-format="YYYY-MM-DD HH:mm:ss"
      />
    </el-form-item>

    <el-row :gutter="20">
      <el-col :span="12">
        <el-form-item label="原价" prop="price">
          <el-input-number
            v-model="gameForm.price"
            :min="0"
            :precision="2"
            :step="10"
            controls-position="right"
          />
          <span class="price-unit">元</span>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="折扣价" prop="priceD">
          <el-input-number
            v-model="gameForm.priceD"
            :min="0"
            :precision="2"
            :step="10"
            controls-position="right"
          />
          <span class="price-unit">元</span>
        </el-form-item>
      </el-col>
    </el-row>

    <el-form-item label="游戏封面" prop="coverImage">
      <el-upload
        class="avatar-uploader"
        :http-request="(e:any) => handleUpload('coverImage', e)"
        list-type="picture-card"
        :file-list="
          gameForm.coverImage
            ? [{ name: '封面', url: gameForm.coverImage }]
            : []
        "
        :limit="1"
        accept="image/*"
        :class="{ hide_box: gameForm.coverImage.length > 0 }"
        :on-remove="() => ([gameForm.coverImage][0] = '')"
      >
        <el-icon class="avatar-uploader-icon"><Plus /></el-icon>
      </el-upload>
    </el-form-item>

    <el-form-item label="游戏展示图">
      <el-upload
        class="avatar-uploader"
        :http-request="(e:any) => handleUpload('displayImages', e)"
        list-type="picture-card"
        :file-list="gameForm.gameInfo.displayImages"
        accept="image/*"
      >
        <el-icon class="avatar-uploader-icon"><Plus /></el-icon>
      </el-upload>
    </el-form-item>

    <el-form-item label="游戏视频">
      <el-upload
        class="avatar-uploader"
        :http-request="(e:any) => handleUpload('displayVideos', e)"
        list-type="picture-card"
        v-model="gameForm.gameInfo.displayVideos"
        accept="video/*"
      >
        <!-- <template #default>
                <video
                  :src="file.url"
                  controls
                  style="width: 100%; height: 100%"
                ></video>
              </template> -->
        <el-icon class="avatar-uploader-icon"><Plus /></el-icon>
      </el-upload>
    </el-form-item>

    <el-form-item label="游戏配置">
      <el-form class="system-requirements-form" label-width="120px">
        <el-form-item label="最低配置">
          <el-form label-position="right" label-width="auto">
            <el-form-item label="操作系统" style="margin-top: 2em">
              <el-input
                v-model="gameForm.gameInfo.systemRequirements.minimum.os"
                placeholder="请输入操作系统要求"
              />
            </el-form-item>
            <el-form-item label="处理器">
              <el-input
                v-model="gameForm.gameInfo.systemRequirements.minimum.processor"
                placeholder="请输入处理器要求"
              />
            </el-form-item>
            <el-form-item label="内存">
              <el-input
                v-model="gameForm.gameInfo.systemRequirements.minimum.memory"
                placeholder="请输入内存要求"
              />
            </el-form-item>
            <el-form-item label="图形处理器">
              <el-input
                v-model="gameForm.gameInfo.systemRequirements.minimum.graphics"
                placeholder="请输入图形处理器要求"
              />
            </el-form-item>
            <el-form-item label="存储">
              <el-input
                v-model="gameForm.gameInfo.systemRequirements.minimum.storage"
                placeholder="请输入存储要求"
              />
            </el-form-item>
          </el-form>
        </el-form-item>

        <el-form-item label="推荐配置" style="margin-left: 20%">
          <el-form label-position="right" label-width="auto">
            <el-form-item label="操作系统" style="margin-top: 2em">
              <el-input
                v-model="gameForm.gameInfo.systemRequirements.recommended.os"
                placeholder="请输入操作系统要求"
              />
            </el-form-item>
            <el-form-item label="处理器">
              <el-input
                v-model="
                  gameForm.gameInfo.systemRequirements.recommended.processor
                "
                placeholder="请输入处理器要求"
              />
            </el-form-item>
            <el-form-item label="内存">
              <el-input
                v-model="
                  gameForm.gameInfo.systemRequirements.recommended.memory
                "
                placeholder="请输入内存要求"
              />
            </el-form-item>
            <el-form-item label="图形处理器">
              <el-input
                v-model="
                  gameForm.gameInfo.systemRequirements.recommended.graphics
                "
                placeholder="请输入图形处理器要求"
              />
            </el-form-item>
            <el-form-item label="存储">
              <el-input
                v-model="
                  gameForm.gameInfo.systemRequirements.recommended.storage
                "
                placeholder="请输入存储要求"
              />
            </el-form-item>
          </el-form>
        </el-form-item>
      </el-form>
    </el-form-item>

    <el-form-item label="游戏介绍文章">
      <Editor
        @editorChange="editorChange"
        :content="gameForm.gameInfo.gameText"
      ></Editor>
    </el-form-item>

    <el-form-item label="游戏下载链接">
      <el-input
        v-model="gameForm.downloadLink"
        placeholder="请输入游戏下载链接"
        clearable
      />
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="submitForm">立即发布</el-button>
      <el-button @click="resetForm">重置</el-button>
    </el-form-item>
  </el-form>
</template>

<script lang="ts" setup>
import { ElMessage } from "element-plus";
import {
  addGameApi,
  addGameDownloadApi,
  getGameDownloadApi,
  getGameInfoApi,
  updateGameApi,
} from "@/apis/game";
import { uploadApi } from "@/apis/upload";
import Editor from "@/components/editer/index.vue";

const props = defineProps({
  type: {
    type: Number,
    default: 0, // 0表示新增，1表示编辑
  },
  id: {
    type: Number,
    default: undefined, // 新增时不传id，编辑时传id
  },
});

const gameForm = ref({
  title: "",
  description: "",
  releaseDate: "",
  price: 0,
  priceD: 0,
  coverImage: "",
  gameInfo: {
    displayImages: [] as string[],
    displayVideos: [] as string[],
    gameText: "",
    systemRequirements: {
      minimum: {
        os: "",
        processor: "",
        memory: "",
        graphics: "",
        storage: "",
      },
      recommended: {
        os: "",
        processor: "",
        memory: "",
        graphics: "",
        storage: "",
      },
    },
  },
  downloadLink: "",
});

// const tempCoverImage = ref("");

const emptyGameForm = ref(JSON.parse(JSON.stringify(gameForm.value)));

// 获取游戏信息
async function getGameInfo() {
  try {
    const res: any = await getGameInfoApi(props.id);
    if (res.code === 0) {
      res.data.coverImage = [{ name: "封面", url: res.data.coverImage }];
      res.data.gameInfo.displayImages = res.data.gameInfo.displayImages.map(
        (item: any) => ({ name: "展示图", url: item })
      );
      gameForm.value = res.data;
      await getGameDownload(res.data.id);
    } else {
      ElMessage.error("获取游戏信息失败");
    }
  } catch (error) {
    ElMessage.error("请求失败");
  }
}

const rules = reactive({
  title: [
    { required: true, message: "请输入游戏标题", trigger: "blur" },
    { min: 2, max: 50, message: "长度在2到50个字符", trigger: "blur" },
  ],
  description: [
    { required: true, message: "请输入游戏描述", trigger: "blur" },
    { min: 10, max: 500, message: "长度在10到500个字符", trigger: "blur" },
  ],
  releaseDate: [
    { required: true, message: "请选择发行日期", trigger: "change" },
  ],
  price: [
    { required: true, message: "请输入游戏价格", trigger: "blur" },
    { type: "number", min: 0, message: "价格不能为负数", trigger: "blur" },
  ],
  coverImage: [
    { required: true, message: "请上传游戏封面", trigger: "change" },
  ],
});

// 上传图片
async function handleUpload(type: string, { file }: any) {
  const formData = new FormData();
  formData.append("file", file);
  try {
    const res: any = await uploadApi(formData);
    if (res.code === 0) {
      if (type === "coverImage") {
        // tempCoverImage.value = res.data;
        gameForm.value.coverImage = res.data;
      } else if (type === "displayImages") {
        gameForm.value.gameInfo.displayImages.push(res.data);
      } else if (type === "displayVideos") {
        gameForm.value.gameInfo.displayVideos.push(res.data);
      }
      ElMessage.success("上传成功");
    } else {
      ElMessage.error("上传失败");
    }
  } catch (error) {
    console.log(error);
    ElMessage.error("上传失败");
  }
}

// 提交表单
async function submitForm() {
  const form = props.id
    ? {
        ...gameForm.value,
        id: props.id,
        coverImage: gameForm.value.coverImage,
        gameInfo: {
          ...gameForm.value.gameInfo,
          displayImages: gameForm.value.gameInfo.displayImages.map(
            (item: any) => item.url
          ),
        },
      }
    : {
        ...gameForm.value,
        coverImage: gameForm.value.coverImage[0],
        gameInfo: {
          ...gameForm.value.gameInfo,
          displayImages: gameForm.value.gameInfo.displayImages.map(
            (item: any) => item.url
          ),
        },
      };
  const api = props.id ? updateGameApi(form) : addGameApi(form);

  const mag = props.id ? "游戏信息更新成功!" : "游戏发布成功!";

  console.log(form);
  console.log(api);
  console.log(props.id);

  try {
    const res: any = await api;
    if (res.code === 0) {
      ElMessage.success(mag);
      if (gameForm.value.downloadLink) {
        await changeDownloadLink();
      }
      resetForm();
    } else {
      ElMessage.error(res.message);
    }
  } catch (error) {
    console.log("error:", error);
    ElMessage.error("请求失败!");
  }
}

const resetForm = () => {
  gameForm.value = JSON.parse(JSON.stringify(emptyGameForm.value));
};

function editorChange(newContent: string) {
  gameForm.value.gameInfo.gameText = newContent;
}

// 更改游戏下载链接
async function changeDownloadLink() {
  try {
    const res: any = await addGameDownloadApi(props.id);
    if (res.code === 0) {
      gameForm.value.downloadLink = res.data;
    } else {
      ElMessage.error("获取游戏下载链接失败");
    }
  } catch (error) {
    ElMessage.error("请求失败");
  }
}

// 获取游戏下载链接
async function getGameDownload(id: any) {
  try {
    const res: any = await getGameDownloadApi(id);
    if (res.code === 0) {
      gameForm.value.downloadLink = res.data;
    } else {
      ElMessage.error("获取游戏下载链接失败");
    }
  } catch (error) {
    ElMessage.error("请求失败");
  }
}

onMounted(() => {
  if (props.type === 1 && props.id) {
    getGameInfo();
  }
});
</script>

<style scoped>
.price-unit {
  margin-left: 10px;
  color: #666;
}

.avatar-uploader {
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
}

.el-upload--picture-card {
  display: none;
}

.hide_box :deep(.el-upload--picture-card) {
  display: none;
}

.system-requirements-form {
  margin-top: 2em;
  width: 100%;
  display: flex;
  /* justify-content: space-between; */
  align-items: center;
}

.system-requirements-form .el-input {
  width: 100%;
  margin-bottom: 10px;
}
</style>
